<?php

namespace Barryvdh\Debugbar\DataCollector;

use DebugBar\DataCollector\DataCollector;
use DebugBar\DataCollector\Renderable;
use Illuminate\Contracts\Support\Arrayable;


class AuthCollector extends DataCollector implements Renderable
{
    
    protected $auth;
    
    protected $showName = false;

    
    public function __construct($auth)
    {
        $this->auth = $auth;
    }

    
    public function setShowName($showName)
    {
        $this->showName = (bool) $showName;
    }

    
    public function collect()
    {
        try {
            $user = $this->auth->user();
        } catch (\Exception $e) {
            $user = null;
        }
        return $this->getUserInformation($user);
    }

    
    protected function getUserInformation($user = null)
    {
                if (is_null($user)) {
            return [
                'name' => 'Guest',
                'user' => ['guest' => true],
            ];
        }

                        $identifier = $user->getAuthIdentifier();
        if (is_numeric($identifier)) {
            try {
                if ($user->username) {
                    $identifier = $user->username;
                } elseif ($user->email) {
                    $identifier = $user->email;
                }
            } catch (\Exception $e) {
            }
        }

        return [
            'name' => $identifier,
            'user' => $user instanceof Arrayable ? $user->toArray() : $user,
        ];
    }

    
    public function getName()
    {
        return 'auth';
    }

    
    public function getWidgets()
    {
        $widgets = [
            'auth' => [
                'icon' => 'lock',
                'widget' => 'PhpDebugBar.Widgets.VariableListWidget',
                'map' => 'auth.user',
                'default' => '{}'
            ]
        ];
        if ($this->showName) {
            $widgets['auth.name'] = [
                'icon' => 'user',
                'tooltip' => 'Auth status',
                'map' => 'auth.name',
                'default' => '',
            ];
        }
        return $widgets;
    }
}
